package org.jeecg.modules.zcgl.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgBaseController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.ImportExcelUtil;
import org.jeecg.common.util.ReflectHelper;
import org.jeecg.modules.activiti.enums.ResultEnum;
import org.jeecg.modules.system.service.IEncodingRulesService;
import org.jeecg.modules.system.service.ISysConfigService;
import org.jeecg.modules.zcgl.entity.AssetImage;
import org.jeecg.modules.zcgl.entity.AssetInfo;
import org.jeecg.modules.zcgl.entity.AssetInfoSub;
import org.jeecg.modules.zcgl.enums.AssetStatusEnum;
import org.jeecg.modules.zcgl.enums.YesNoEnum;
import org.jeecg.modules.zcgl.service.*;
import org.jeecg.modules.zcgl.vo.AssetInfoPage;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Description: 资产信息
 * @Author: jeecg-boot
 * @Date: 2020-06-19
 * @Version: V1.0
 */
@Api(tags = "资产信息")
@RestController
@RequestMapping("/zcgl/assetInfo")
@Slf4j
public class AssetInfoController extends JeecgBaseController<AssetInfoPage, AssetInfo, IAssetInfoService> {

    @Autowired
    private IAssetInfoService assetInfoService;
    @Autowired
    private IAssetInfoSubService assetInfoSubService;
    @Autowired
    private IAssetImageService assetImageService;
    @Autowired
    private ILeaseContractInfoService leaseContractInfoService;
    @Autowired
    private ISysConfigService sysConfigService;
    @Autowired
    private IAssetContractLogService assetContractLogService;
    @Autowired
    private IEncodingRulesService encodingRulesService;

    /**
     * 分页列表查询
     *
     * @param assetInfo
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "资产信息-分页列表查询")
    @ApiOperation(value = "资产信息-分页列表查询", notes = "资产信息-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(AssetInfo assetInfo,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        System.out.println(JSON.toJSONString(req.getParameterMap()));
        QueryWrapper<AssetInfo> queryWrapper = QueryGenerator.initQueryWrapper(assetInfo, req.getParameterMap());
        Page<AssetInfo> page = new Page<AssetInfo>(pageNo, pageSize);
        IPage<AssetInfo> pageList = assetInfoService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param assetInfoPage
     * @return
     */
    @AutoLog(value = "资产信息-添加")
    @ApiOperation(value = "资产信息-添加", notes = "资产信息-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody AssetInfoPage assetInfoPage) {
        assetInfoService.saveMain(assetInfoPage);
        return Result.ok("添加成功！");
    }

    /**
     * 检测数据是否正常
     *
     * @param assetInfoPage
     * @return
     */
    @AutoLog(value = "资产信息-检测数据是否正常")
    @ApiOperation(value = "资产信息-检测数据是否正常", notes = "资产信息-检测数据是否正常")
    @PostMapping(value = "/checkModel")
    public Result<?> checkModel(@RequestBody AssetInfoPage assetInfoPage) {
        assetInfoService.checkModel(assetInfoPage);
        return Result.ok("检测通过！");
    }


    @AutoLog(value = "资产信息-处置")
    @ApiOperation(value = "资产信息-处置", notes = "资产信息-处置")
    @PostMapping(value = "/assetDisposal")
    public Result<?> assetDisposal(AssetInfo vo) {
        if (vo.getAssetDisposal() == null) {
            return Result.error("请选择处置类型");
        }
        AssetInfo assetInfo = assetInfoService.getById(vo.getId());
        if (assetInfo == null) {
            return Result.error("资产信息不存在");
        }
//        if (assetInfo.getHasContractQuantity() != null && assetInfo.getHasContractQuantity().intValue() > 0){
//            return Result.error("资产有合同存在，处置失败！");
//        }
        int num = assetContractLogService.countNum(assetInfo.getId(), null, null, YesNoEnum.NO.getStatus());
        if (num > 0){
            return Result.error("资产有合同存在，处置失败！");
        }
//        LambdaQueryWrapper<LeaseContractInfo> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(LeaseContractInfo::getAssetId, assetInfo.getId());
//        queryWrapper.in(LeaseContractInfo::getStatus, LeaseContractStatusEnum.TAKE_EFFECT.getStatus(), LeaseContractStatusEnum.RENEW.getStatus());
//        if (leaseContractInfoService.isHasByTo(queryWrapper)) {
//            return Result.error("资产有合同存在，处置失败！");
//        }
        if (vo.getAssetDisposalDate() == null){
            vo.setAssetDisposalDate(new Date());
        }
        assetInfo.setStatus(AssetStatusEnum.ASSET_DISPOSAL.getStatus());
        assetInfo.setAssetDisposalDescription(vo.getAssetDisposalDescription());
        assetInfo.setAssetDisposal(vo.getAssetDisposal());
        assetInfo.setAssetDisposalDate(vo.getAssetDisposalDate());
        assetInfoService.updateById(assetInfo);
        return Result.ok("处置成功！");
    }

    /**
     * 编辑
     *
     * @param assetInfoPage
     * @return
     */
    @AutoLog(value = "资产信息-编辑")
    @ApiOperation(value = "资产信息-编辑", notes = "资产信息-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody AssetInfoPage assetInfoPage) {
        AssetInfo assetInfo = service.getById(assetInfoPage.getId());
        if (assetInfo == null) {
            throw new JeecgBootException("资产不存在！");
        }
        String isApproval = sysConfigService.getValueByKey(CommonConstant.IS_APPROVAL);
        if (assetInfo.getStatus().intValue() != AssetStatusEnum.DRAFT.getStatus()){
            if ("1".equals(isApproval) &&
                    (assetInfo.getProcessStatus() == null
                            || ResultEnum.RESULT_PASS.getStatus() != assetInfo.getProcessStatus().intValue())) {
                throw new JeecgBootException("未审批通过，不能编辑！");
            }
        }
        System.out.println("进入此处");
        assetInfoService.updateMain(assetInfoPage,true);
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "资产信息-通过id删除")
    @ApiOperation(value = "资产信息-通过id删除", notes = "资产信息-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        assetInfoService.delMain(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "资产信息-批量删除")
    @ApiOperation(value = "资产信息-批量删除", notes = "资产信息-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.assetInfoService.delBatchMain(Arrays.asList(ids.split(CommonConstant.DEFAULT_SEPARATOR)));
        return Result.ok("批量删除成功！");
    }

    /**
     * 统计面积
     *
     * @param ids
     * @return
     */
//    @AutoLog(value = "资产信息-批量删除")
    @ApiOperation(value = "资产信息-统计面积", notes = "资产信息-统计面积")
    @GetMapping(value = "/queryTotalAreaByIds")
    public Result<?> queryTotalAreaByIds(@RequestParam(name = "ids", required = true) String ids) {
        BigDecimal totalArea = this.assetInfoService.queryTotalAreaByIds(ids);
        return Result.ok(totalArea);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "资产信息-通过id查询")
    @ApiOperation(value = "资产信息-通过id查询", notes = "资产信息-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        AssetInfo assetInfo = assetInfoService.getById(id);
        if (assetInfo == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(assetInfo);

    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "资产明细通过主表ID查询")
    @ApiOperation(value = "资产明细主表ID查询", notes = "资产明细-通主表ID查询")
    @GetMapping(value = "/queryAssetInfoSubByMainId")
    public Result<List<AssetInfoSub>> queryAssetInfoSubListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<AssetInfoSub> assetInfoSubList = assetInfoSubService.selectByMainId(id);
        return Result.ok(assetInfoSubList);
    }

    @AutoLog(value = "资产图片通过主表ID查询")
    @ApiOperation(value = "资产图片通过主表ID查询", notes = "资产图片-通主表ID查询")
    @GetMapping(value = "/queryAssetImageListByMainId")
    public Result<List<AssetImage>> queryAssetImageListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<AssetImage> images = assetImageService.selectByMainId(id);
        return Result.ok(images);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param assetInfo
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, AssetInfo assetInfo) {
        return super.exportXls(request, assetInfo, AssetInfoPage.class, "资产信息");
    }

    @Override
    public List<AssetInfoPage> exportList(List<AssetInfo> list) {
        List<AssetInfoPage> pageList = new ArrayList<AssetInfoPage>();
        if (list != null){
            list.stream().forEach(item -> {
                AssetInfoPage vo = new AssetInfoPage();
                BeanUtils.copyProperties(item, vo);
                List<AssetInfoSub> assetInfoSubList = assetInfoSubService.selectByMainId(item.getId());
                vo.setAssetInfoSubList(assetInfoSubList);
//				vo.setAssetImageList(assetImageService.selectByMainId(main.getId()));
                pageList.add(vo);
            });
//			for (AssetInfo main : list) {
//			}
        }
        return pageList;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        String assetType = request.getParameter("assetType");
        return importAssetInfoExcel(request, response,assetType);
    }


    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    private  Result<?> importAssetInfoExcel(HttpServletRequest request, HttpServletResponse response,String assetType) {
        try {
            List<AssetInfoPage> list = super.importExcelBase(request, response, AssetInfoPage.class);
            //update-begin-author:taoyan date:20190528 for:批量插入数据
            long start = System.currentTimeMillis();

            // 错误信息
            List<String> errorMessage = new ArrayList<>();
            AtomicInteger successLines = new AtomicInteger();
            AtomicInteger errorLines = new AtomicInteger();

            list.stream().forEach(vo -> {
                try {
                    vo.setAssetType(assetType);
                    boolean bool = this.importSave(vo);
                    if (bool) {
                        successLines.getAndIncrement();
                    } else {
                        errorLines.getAndIncrement();
                        //                            errorMessage.add("导入失败:" + JSON.toJSONString(vo));
                        errorMessage.add("第" + vo.getRowNumber() + "行数据：导入失败。");
                    }
                } catch (JeecgBootException e) {
                    errorLines.getAndIncrement();
                    errorMessage.add("第" + vo.getRowNumber() + "行数据：" + e.getMessage() + "。");
                    //                        errorMessage.add("导入失败:" + e.getMessage() + "-" + JSON.toJSONString(vo));
                } catch (Exception e) {
                    errorLines.getAndIncrement();
                    log.error(e.getMessage(), e);
                    errorMessage.add("第" + vo.getRowNumber() + "行数据：导入失败。");
                    //                        errorMessage.add("导入失败:" + e.getMessage() + "-" + JSON.toJSONString(vo));
                }
            });
            log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
            return ImportExcelUtil.imporReturnRes(errorLines.get(), successLines.get(), errorMessage);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("文件导入失败！" + e.getMessage());
        }
//        return Result.error("文件导入失败！");
    }

    @Override
    public boolean importSave(AssetInfoPage vo) {
        assetInfoService.saveMain(vo);
//        assetInfoService.importSaveMain(vo);
        return true;
    }


    /**
     * 获取资产编码
     *
     * @return
     */
    @AutoLog(value = "资产信息-获取资产编码")
    @ApiOperation(value = "资产信息-获取资产编码", notes = "资产信息-获取资产编码")
    @GetMapping(value = "/getAssetCode")
    public Result<?> getAssetCode(@RequestParam(name = "companyId", required = true) String companyId) {
     String code =  encodingRulesService.getNextCoding(YesNoEnum.NO.getStatus(), null, null,
             "asset_code", companyId);
        return Result.ok(code);

    }
}
